package com.boot.project.service.impl;

import com.boot.project.dao.CommentDao;
import com.boot.project.dao.InfoDao;
import com.boot.project.domain.CommentDo;
import com.boot.project.domain.InfoDo;
import com.boot.project.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private InfoDao infoDao;

    @Override
    public Map<String, Object> save(CommentDo commentDo) {
        Map<String, Object> mapResult = new HashMap<>();
        Integer saveFlag = commentDao.save(commentDo);
        // 评论新增之后，资讯表中对应的那条资讯的评论数就得加一
        InfoDo infoDo = infoDao.getInfo(commentDo.getInfoId());
        infoDo.setComments(infoDo.getComments() + 1);
        Integer updateFlag = infoDao.setComments(infoDo);
        if (saveFlag >= 0 && updateFlag >= 0) {
            mapResult.put("msg", "ok");
            mapResult.put("code", 200);
            return mapResult;
        } else {
            mapResult.put("msg", "error");
            mapResult.put("code", 500);
            return mapResult;
        }
    }

    @Override
    public List<CommentDo> list(Long infoId) {
        List<CommentDo> allResult = commentDao.list(infoId);
        List<CommentDo> result = new ArrayList<>();
        if (allResult.size() <= 5) {
            return result;
        } else {
            for (int i = 0; i <= allResult.size() / 2; i++) {
                result.add(allResult.get(i));
            }
            return result;
        }
    }
}
